import React from "react";
import { connect } from "react-redux";
import { Input, Form, Modal, Select, DatePicker, Row, Col } from "antd";
import { cloneDeep, intersectionBy } from "lodash";
import fetch from "../../utils/fetch";
import crypto from "crypto";
import { courseBeans } from "../../constants/";
import moment from "moment";

const dateFormat = "YYYY-MM-DD";
const today = moment(new Date(), dateFormat).format(dateFormat);

const FormItem = Form.Item;
const Option = Select.Option;

class CourseModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  handleSave = () => {
    const { form, action, course } = this.props;
    form.validateFieldsAndScroll((errors, values) => {
      if (errors) {
        return;
      }
      values = cloneDeep({ ...course, ...values });


      fetch("/api/updateCourse", values).then(() => {
        this.props.onCancel();
        this.props.onSearch();
      });
    });
  };

  tagGenerator = ({ title, key, tag, options, required = false }) => {
    const { form, course } = this.props;
    const { getFieldDecorator } = form;
    const initialValue =
      tag !== "date"
        ? (course[key])
        : (course[key] ? moment(course[key], dateFormat) : null);
    let comp = null;
    if (tag === "input") {
      comp = <Input placeholder={"请输入" + title} />;
    } else if (tag === "select") {
      comp = (
        <Select placeholder={"请选择" + title}>
          {options.map(o => (
            <Option key={o} value={o}>
              {o}
            </Option>
          ))}
        </Select>
      );
    } else if (tag === "date") {
      comp = (
        <DatePicker
          style={{ width: "100%" }}
          format={dateFormat}
          placeholder={"请输入" + title}
        />
      );
    }

    return (
      <Col span={8} key={key}>
        <FormItem label={title}>
          {getFieldDecorator(key, {
            rules: [
              {
                required,
                message: title + '必填'
              }
            ],
            initialValue
          })(comp)}
        </FormItem>
      </Col>
    );
  };

  render() {
    const { form, visible, onCancel, action } = this.props;
    return (
      <Modal
        title={(action === "add" ? "新建" : "修改") + "用户"}
        visible={visible}
        onOk={this.handleSave}
        onCancel={onCancel}
        width={action !== "mPasswd" ? 720 : 480}
      >
        <form>
          <Row gutter={16} type="flex" align="top">
            {courseBeans.map(ub => {
              return this.tagGenerator(ub);
            })}
          </Row>
        </form>
      </Modal>
    );
  }
}

export default connect()(Form.create()(CourseModal));
